<template>
	<view class="">
		<uni-popup ref="popup" :isMaskClick="isMaskClick" style="left: 20rpx;right:20rpx" background-color="transparent"
			@maskClick="maskClick">
			<view class="popupView">
				<view class="popupViewContent">
					<view v-if="true" class="uni-share-contents bgc-color" style="">
						<view class="title1">{{$t('General.device.DeviceManagement2')}}</view>
					    <view v-if="device.deviceNo" class="title2">
						    {{maskedStrings(device.deviceNo)}}
					    </view>
					</view>
					<template v-for="(item,index) in list">
						<view :key="index" v-if="item.status" class="uni-share-content bgc-color"
							@click="itemClick(item,index)"
							style="display: flex;justify-content: space-between;align-items: center;">
							<view class="leftTitle"></view>
							<view class="title">{{item.title}}</view>
							<view class="subTitle">{{item.subTitle}}</view>
						</view>
					</template>
				</view>
				<view class="uni-share-button-box" @click="close">
					<text style="color:#2CBDB8 ;">{{ $t('General.family.cancel') }}</text>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="inputDialog" type="dialog" :is-mask-click="isMaskClick" class="popupName">
			<view class="form">
				<view class="u-f-ajc title">提示</view>
				<view style="text-align: center;" class="form-item-content form-item">
					{{title}}
				</view>
				<view v-if="buttonType == 'save' || buttonType == 'close'" class="u-f-r form-item">
					<view class="u-f-ajc cancel" @click="closeDialog">取消</view>
					<view v-if="buttonType == 'save'" class="u-f-ajc conf" @click="onOpen">开启</view>
					<view v-if="buttonType == 'close'" class="u-f-ajc conf" @click="onClose">关闭</view>
				</view>
				<view v-else class="u-f-r form-item">
					<view v-if="buttonType == 'close'" class="u-f-ajc conf" @click="submit">确定</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="shareDialog" type="dialog" :is-mask-click="isMaskClick" class="popupName">
			<view class="form">
				<view class="u-f-ajc title">提示</view>
				<view style="text-align: center;" class="form-item-content form-item">
					需要将您的家人邀请至[<text :class="currentGroupName?'textColor':''">{{currentGroupName?currentGroupName:'该家庭组下'}}</text> ]才能分享该设备。
				</view>
				<view class="u-f-r form-item">
					<view class="u-f-ajc cancel" @click="closeDialog">取消</view>
					<view class="u-f-ajc conf">
						<button class="share-button" @click="shareConfig" open-type="share">确定</button>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="shareDevice" type="dialog" :is-mask-click="isMaskClick">
			<view class="form">
				<uni-icons class="close" size="25" type="closeempty" color="#999999" @click="closeShareDevice"></uni-icons>
				<view class="u-f-ajc u-f-c title">
					<view class="">提示</view>
					<image class="img" src="https://statics.xmcsrv.net/weixin/shareDevice.png"></image>
				</view>
				<view class="form-item u-f-c desc">
					<text>分享设备：</text>
					<text>仅将当前设备分享给好友</text>
					<text style="margin-top: 20rpx;">分享家庭：</text>
					<text>将当前设备所在家庭下的所有设备分享给好友，包括此设备</text>
				</view>
				<view class="u-f-r form-item">
					<button class="u-f-ajc cancel" @click="shareType('device')" open-type="share">分享设备</button>
					<view class="u-f-ajc conf">
						<button class="share-button" @click="shareType('family')">分享家庭</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const {
		maskedString
	} = require('@/utils/util.js');
	export default {
		name: "popup",
		props: {
			list: {
				type: Array,
				default () {
					return [];
				}
			},
			device: {
				type: Object,
				default () {
					return {};
				}
			},
			isMaskClick: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				title: '开启后，可主动在手机上打开设备页面。下次唤醒门锁后生效',
				buttonType: 'save',
				shareMessage: '',
				currentGroupName:"",
				isMaxCount:false,
				privileges:[],
				singleShareInfo:'',
			}
		},
		inject: ['getShareInfo'],
		methods: {
			maskedStrings(e){
				return maskedString(e)
			},
			maskClick() {
				this.close()
			},
			open() {
				this.$refs.popup.open('bottom')
			},
			close() {
				this.$refs.popup.close();
				this.showTabBar()
			},
			// 开启主动查看
			onOpen() {
				// this.getlogin(0)
				this.setTailoredConfig(0)
			},
			// 关闭主动查看
			onClose() {
				// this.getlogin()
				let status = this.device.status
				console.log('设备=======', this.device, status);
				if (status.status == 'online') {
					if (status.wakeUpStatus == '1' || status.wakeUpStatus == '2') { //已唤醒 准备休眠中(从预览页退回到首页)
						this.getlogin('online')
						this.setTailoredConfig(1, 'online')
					} else {
						this.setTailoredConfig(1, 'offline')
					}
				} else {
					this.setTailoredConfig(1, 'offline')
				}
			},
			closeDialog() {
				this.$refs.inputDialog.close();
				this.$refs.shareDialog.close();
				this.showTabBar()
			},
			// 点击某一个item
			itemClick(item, index) {
				// console.log(item, index)
				// title:`${ev.deviceName}(${desensitization(ev.deviceNo,8,-4)})`,
				// this.$emit('click', item);
				let ev = this.device
				switch (item.type) {
					case 'cloud':
						uni.navigateTo({
							url: `/jvss/pagesDevice/device/device-live/door-lock/message?device=${encodeURIComponent(JSON.stringify(ev))}`
						});
						break;
					case 'set':
					    this.saveLoginInfo()
						let url =
							`/jvss/pagesDevice/device/device-live/door-lock/setting/setting?device=${encodeURIComponent(JSON.stringify(ev))}`
						if (item.path) {
							url = `${item.path}?device=${encodeURIComponent(JSON.stringify(ev))}&type=${'tab'}`
						}
						uni.navigateTo({
							url: url
						});
						break;
					case 'room':
						uni.navigateTo({
							url: `/jvss/pagesDevice/device/room-select/room-select?device=${encodeURIComponent(JSON.stringify(ev))}&type=3`
						});
						this.showTabBar()
						break;
					case 'copy':
						uni.setClipboardData({
							data: ev.deviceNo,
							success: () => {
								uni.showToast({
									title: this.$t('General.device.copySuccess')
								})
							}
						});
						break;
					case 'share':
						if(this.isMaxCount){
							uni.showToast({
								title: this.$t('General.device.DeviceManagement1'),
								icon:'none'
							})
							return
						}
						let currentGroupName = uni.getStorageSync('currentGroupName')
						this.currentGroupName = currentGroupName;
						// this.$refs.shareDialog.open();
						this.$refs.shareDevice.open();
						this.getPrivilegeByPid(this.device.parentPid)
						break;
					case 'delete':
						let deviceNo = this.device.deviceNo;
						this.delDevice(deviceNo);
						break;
					case 'active':
						this.active(item)
						break;
					case 'removeShare':
						this.delRecDevice(this.device)
						break;
					case 'pass':
						uni.navigateTo({
							url: `/jvss/pagesDevice/device/device-live/door-lock/temporaryLx?device=${encodeURIComponent(JSON.stringify(ev))}`
						});
						this.showTabBar()
						break;

				}
				if (item.type == 'active' || item.type == 'share') {
					this.$refs.popup.close();
				} else {
					this.close()
				}
			},
			//关闭分享单个设备弹框
			closeShareDevice(){
				this.$refs.shareDevice.close();
			},
			//分享单个设备或家庭
			shareType(type){
				if(type == 'device'){
					this.getShareInfo(this.singleShareInfo)
					this.closeShareDevice()
				}else{
					this.closeShareDevice()
					this.$refs.shareDialog.open();
				}
			},
			//单个设备分享
			shareSingleDevice(ev){
				let data = {
					deviceSn:ev.deviceNo,
					privileges:this.privileges.length==0?['all']:this.privileges
				}
				getApp().globalData.api.shareSingleDevice(data, (result) => {
					console.log('单个设备分享',result);
					this.singleShareInfo = result
					// this.getShareInfo(this.shareMessage)
				})
			},
			//根据主pid查询可分享权限列表
			getPrivilegeByPid(pid){
				let data = {
					pid:pid
				}
				getApp().globalData.api.getPrivilegeByPid(data, (result) => {
					console.log('获取分享权限',result);
					this.privileges = result
				})
			},
			//接受分享者删除被分享的设备
			delRecDevice(item){
				console.log('移除分享',item);
				let data = {
					id:item.sharedVO.id
				}
				getApp().globalData.api.delRecDevice(data, (result) => {
					console.log('接受分享者删除被分享的设备',result);
                    let data1 = {
                        token: item.token,
                        deviceNo: item.deviceNo
                    }
                    getApp().globalData.api.cancelSubscribeMessage(data1, (result) => {
                        uni.showToast({
                            title: '成功删除！',
                            success: () => {
                                getApp().globalData.mqtt.getUnsubscribe(item.deviceNo,'device')
                                this.$emit('delete',{type:'shareDevice'});
                            }
                        });
                    });

				})
			},
			// 缓存设备信息
			saveLoginInfo() {
				let deviceList = uni.getStorageSync('deviceList') || [];
				let isCache = false
				deviceList.forEach((item) => {
					if (this.device.deviceNo == item.deviceNo) {
						isCache = true
					}
				})
				if (!isCache) {
					deviceList.push(this.device);
				}
				uni.setStorageSync('deviceList', deviceList);
			},
			shareConfig() {
				this.$refs.shareDialog.close();
			},
			active(e) {
				console.log(e);
				if (e.subTitle == '未开启') {
					this.buttonType = 'save';
					this.title = '开启后，可主动在手机上打开设备页面。下次唤醒门锁后生效。';
				} else {
					this.title = '关闭后，将进一步延长电池使用时间，但无法主动在手机上打开设备页面。';
					this.buttonType = 'close';
				}
				this.openDialog()
			},
			getlogin(status) {
				uni.showLoading({
					mask: true
				});
				let data = {
					encryptType: 'DISABLE',
					LoginType: 'DVRIP-Web',
					UserName: 'admin',
					PassWord: this.device.devPassWord,
					Name: 'generalinfo'
				};
				if (this.device.adminToken) {
					data.LoginToken = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let token = this.device.token
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					uni.hideLoading();
					// console.log(result)
					this.$logs({
						info: '关闭主动查看时登录',
						device: this.device,
						result: result
					})
					if (result.data.code === 2000) {
						if (result.data.data.Ret === 100 || result.data.data.Ret === 104) {
							if (status == 'online') {
								this.setconfig()
							} else {
								this.deviceLogOut()
							}
						} // 出错
						else {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data.Ret] ||
									result.data.data.RetMsg,
								icon: "none"
							})

						}
					} else {
						uni.showToast({
							title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result
								.data.msg,
							icon: 'none',
						});
					}
				});
			},
			//设备退出
			deviceLogOut() {
				let token = this.device.token
				let data = {
					Name: 'Logout',
				};
				getApp().globalData.api.deviceLogOut(data, token, (result) => {
					console.log(result, '首页登出')
				});
			},
			setconfig() {
				uni.showLoading({
					mask: true
				});
				let token = this.device.token
				let data = {
					"Name": "Consumer.SwitchWifiMode",
					"Consumer.SwitchWifiMode": {
						"WifiMode": 1 //1关闭  0开
					}
				};
				getApp().globalData.api.setconfig(data, token, (result) => {
					uni.hideLoading();
					console.log('成功', result)
					if (result) {
						// console.log('成功')
					}
					this.$refs.inputDialog.close();
					this.showTabBar()
					// console.log(result);
					this.deviceLogOut()
				}, false, false);
			},
			setTailoredConfig(type, status) {
				uni.showLoading({
					mask: true
				});
				let token = this.device.token
				let data = {
					"sn": this.device.deviceNo,
					"data": {
						"Consumer.SwitchWifiMode": {
							"WifiMode": type,
						}
					}
				};
				getApp().globalData.api.setTailoredConfig(data, token, (result) => {
					uni.hideLoading();
					if (result) {
						// console.log('成功')
						if (type == 1 && status == 'offline') {
							this.getlogin()
						}
					}
					this.$refs.inputDialog.close();
					this.showTabBar()
					// console.log(result);
				});
			},
			openDialog() {
				this.$refs.inputDialog.open()
			},
			//邀请
			onBindtapAddUser() {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId')
				}
				getApp().globalData.api.getKey(data, result => {
					console.log(result);
					if(result.data.code == 2000){
						this.shareMessage = result.data.data;
						this.getShareInfo(this.shareMessage)
						this.isMaxCount = false
					}else if(result.data.code == -91005){
						this.isMaxCount = true
					}
				},false)
			},
			// 删除设备
			delDevice(deviceNo) {
				let deviceList = uni.getStorageSync('deviceList');
				if (deviceList) {
					deviceList = deviceList.filter(item => item.deviceNo !== this.device.deviceNo); //删除对应序列号的缓存数据
				}
				console.log(deviceList);
				uni.showModal({
					title: this.$t('General.family.tip'),
					content: this.$t('General.device.DeviceManagement3'),
					success: (response) => {
						if (response.confirm) {
							const data = {
								deviceNo: deviceNo,
								clearNss: false
							};
							getApp().globalData.api.delDevice(data, (result) => {
								if (deviceList) {
									uni.setStorageSync('deviceList', deviceList);
								}
								uni.showToast({
									title: this.$t('General.family.msg8'),
									success: () => {
										// this.getDeviceListByPage();
										getApp().globalData.mqtt.getUnsubscribe(deviceNo,'device')
										uni.removeStorageSync(this.device.deviceNo)
										this.$emit('delete');
										uni.$emit('delDevice')
										uni.setStorageSync('isDeleteDevice', true)
									}
								});
							});
						}
					}
				});
			},
			showTabBar() {
				setTimeout(() => {
					uni.showTabBar();
				}, 200)
				setTimeout(() => {
					uni.$emit('refreshSize')//刷新新UI高度
				}, 300)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.popupName {
		/deep/ .uni-popup__wrapper {
			top: -100rpx;
		}
	}
	.uni-share-content {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		background: white;
		min-height: 50px;
		background-color: #fff;
		border-top: 1rpx solid #eee;
	}
    .uni-share-contents {
		min-height: 50px;
		background-color: #fff;
		text-align: center;
		overflow: hidden;
		.title1{
			font-size: 30rpx;
			font-weight: bold;
			margin: 5px 0;
		}
		.title2{
			font-size: 22rpx;
			font-weight: 400;
			margin: 3px 0;
		}
	}
	.popupViewContent {
		border-radius: 12rpx;
		overflow: hidden;
	}

	.share-button {
		border-radius: 0;
		line-height: 50rpx;
	}

	.share-button::after {
		border: none;
	}

	.sheet {
		flex-direction: column;
		display: flex;
		padding: 0 10rpx
	}

	.uni-share-button-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		padding: 10px 20px;
		display: flex;
		justify-content: center;
		background: white;
		margin-top: 20rpx;
		border-radius: 10rpx;
	}

	.icon {
		width: 50rpx;
		height: 50rpx;
		margin-left: 20rpx;
	}

	.u-tips {
		font-size: 26rpx;
		text-align: center;
		padding: 34rpx 0;
		line-height: 1;
		color: #ff00ff;
	}

	.leftTitle {
		width: 25%;
	}

	.title {
		width: 50%;
		text-align: center;
		font-size: 28rpx;
		line-height: 80rpx;
	}

	.subTitle {
		width: 25%;
		font-size: 24rpx;
		color: #2CBDB8;
		text-align: center;
	}

	.popupView {
		width: auto;
		// height: 30vh;
		overflow: hidden;
		border-radius: 5px;
		padding: 5px;
		margin: 10px;
		background: transparent;
	}

	.form {
		background: white;
		padding: 40rpx;
		border-radius: 20rpx;
		position: relative;
		.title {
			font-size: 34rpx;
			font-weight: bold;
			line-height: 49rpx;
			color: #464646;
			width: 100%;
		}
		.img{
			width: 230rpx;
			height: 230rpx;
			margin-top: 20rpx;
		}
		.close{
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			width: 50rpx;
			height: 50rpx;
		}

		.form-item-content {
			width: 70vw;
			
			.textColor{
			    color: #2CBDB8;
			}
		}

		.form-item {
			margin-top: 40rpx;
			.cancel {
				background: #F6F7FB;
				color: #000000;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
				&::after{
					border: none;
				}
			}

			.conf {
				margin-left: 20rpx;
				background: #FF0025;
				color: #ffffff;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
				overflow: hidden;

				.share-button {
					width: 100%;
					background: none;
					color: #ffffff;
				}

				.share-button::after {
					border: none;
				}
			}
		}

		.u-f-r {
			justify-content: space-between;
		}

		.form-title {
			text-align: center;
			margin-bottom: 40rpx;
			font-weight: bold;
		}
	}

	.bgc-color:active {
		background-color: #eeeeee;
	}
	.desc{
		text-align: left;
		color: #999;
		font-size: 26rpx;
		padding: 0 30rpx;
		width: 60vw;
	}
</style>
